<?php

namespace app\cardeadmin\controller;

use app\api\controller\PublicApi;
use app\common\controller\AdminController;
use app\common\model\Cards as cardsModel;
use app\common\model\CardsTrans;
use app\common\model\CardsTransOne;
use app\common\model\CardsTransTwo;
use app\common\model\ManageLog;
use app\common\model\MonitorCard;
use app\common\model\MonitorCardDiff;
use app\common\model\SearchTrans;
use app\common\model\UserCashError;
use app\common\model\UserCashLog;
use app\common\model\UserSet;
use think\facade\Db;
use think\facade\View;
use think\facade\Cache;

/**
 * 余额管理
 * Class ArticleType
 * @package app\manage\controller
 */
class Toolbar extends AdminController
{

    public function index()
    {
        if($this->request->isAjax()){
            $fcModel = new CardsTrans();
            return $fcModel->getCardShops(input('param.'));
        }
        return View::fetch();
    }

    public function getNewBin()
    {
        if($this->request->isAjax()){
            $old_set = Db::name('user_set')->where(['id' => 1])->find();
            $bank_type_list = json_decode($old_set['card_set'] , true);
            $bank_new = [];
            foreach ($bank_type_list as $k=>$v){
                if($v['bank_type'] == 3)
                {
                    $bank_new[] = $v['card_type'];
                }
            }

            $send_param = [
                'action_type' => 'get_new_bin'
            ];
            $list = PublicApi::requestApi('Connexpay2',$send_param);
            $list_data = $list['list'];
            foreach ($list_data as $k_data => &$v_data){
                if(in_array(substr($v_data['cardBin'] , 0 , 6) , $bank_new)){
                    $v_data['is_used'] = 1;
                }else{
                    $v_data['is_used'] = 0;
                }
            }
            return $result = [
                'code'  => 0,
                'msg'   => lang('get info success'),
                'data'  => $list_data,
                'count' => count($list_data),
            ];
        }
        return View::fetch();
    }

    public function cardDelList()
    {
        if($this->request->isPost()) {
            $data = input('param.');
            $cdModel = new cardsModel();
            return $cdModel->tableDataDel($data);
        }
        $card_num = trim(input('get.card_num'));
        $cycleAmountLimitUsed   = 0.00;
        $cycleAmountLimitHold   = 0.00;
        $api_amount             = 0.00;
        $api_amount_total       = 0.00;
        $cardStatus             = '---';
        if(!empty($card_num) && substr($card_num ,0 ,6) == 556766){
            $send_param         = [
                "user_id"       => 0,
                "action_type"   => "searchExpDate2",
                "card_type"     => 556766,
                "post_param"    => [
                    "card_num"  => $card_num,
                ]
            ];
            $check_card_api = PublicApi::requestApi('Comdata',$send_param);
            $return_blog    = $check_card_api['blog'];
            $return_list    = $check_card_api['list'];
            if($return_blog) {
                $api_amount       = $return_list['cycleAmountLimitAvailable'];
                $api_amount_total = $return_list['cycleAmountLimit'];
                $cycleAmountLimitUsed = $return_list['cycleAmountLimitUsed'];
                $cycleAmountLimitHold = $return_list['cycleAmountLimitHold'];
                $cardStatus       = $return_list['cardStatus'];
            }
        }
        View::assign([
            'api_amount_total'  => $api_amount_total,
            'api_amount'        => $api_amount,
            'amount_used'       => $cycleAmountLimitUsed,
            'amount_hold'       => $cycleAmountLimitHold,
            'card_num'          => $card_num,
            'card_status'       => $cardStatus
        ]);
        return View::fetch();
    }

    public function searchTrans()
    {
        if($this->request->isAjax()){
            $card_num = trim(input('post.card_num' , ''));
            $date_time= trim(input('post.datetime', ''));
            $tran_status = input('post.tran_status', '');

            $data       = [];
            $result = [
                'code'  => 0,
                'msg'   => lang('get info success'),
                'data'  => [],
                'param' => [
                    'card_num' => empty($card_num) ? 'NULL' : $card_num,
                    'username' => 'NULL',
                    'bank_type'=> 'NULL',
                    'time'     => 'NULL',
                    'balance'  => 'NULL',
                    'status'   => 'NULL',
                    'limit'    => 'NULL'
                ],
                'count' => 0,
            ];
            if(!empty($card_num)){
                $card_list = Db::name('cards')->where(['card_num'=>$card_num])->find();
                if(!empty($card_list)){
                    $card_type = $card_list['card_type'];
                    $bank_type = $card_list['bank_type'];
                    $card_token= $card_list['card_token'];
                    $user_id   = $card_list['user_id'];
                    $user_name = Db::name('user')->where(['id'=>$user_id])->value('username');
                    $result['param'] = [
                        'card_num' => $card_num,
                        'username' => $user_name,
                        'bank_type'=> $bank_type,
                    ];
                    if($bank_type == 3){
                        //查询卡余额
                        $search_card_detail_send         = [
                            "user_id"       => $user_id,
                            "card_num"      => $card_num,
                            "cardGuid"      => $card_token,
                            "action_type"   => "getCardDetail"
                        ];
                        $card_detail_api = PublicApi::requestApi('Connexpay',$search_card_detail_send);
                        $return_blog_detail    = $card_detail_api['blog'];
                        $return_list_detail    = $card_detail_api['list'];
                        if($return_blog_detail) {
                            $result['param']['balance'] = $return_list_detail['availableBalance'] ?? 0.00;
                            $result['param']['limit']   = $return_list_detail['amountLimit'] ?? 0.00;
                            $result['param']['status']  = $return_list_detail['status'] ?? 'NULL';
                        }
                        //搜索消费日志
                        $result['param']['time'] = 'all';
                        $send_tran_param         = [
                            "user_id"       => 0,
                            "card_num"      => $card_num,
                            "cardGuid"      => $card_token,
                            "action_type"   => "get_tran"
                        ];
                        $send_api = PublicApi::requestApi('Connexpay',$send_tran_param);
                        $return_blog    = $send_api['blog'];
                        $return_list    = $send_api['list'];
                        if($return_blog){
                            if(isset($return_list['transactions'])){
                                $transactions_list = array_reverse($return_list['transactions']);
                                foreach ($transactions_list as $k_tran=>$v_tran){
                                    $api_tran_status = $v_tran['status'];
                                    $api_tran_type   = $v_tran['type'];
                                    $api_tran_token   = $v_tran['transactionGuid'];
                                    $timestamp = substr(str_replace('T' , ' ' ,$v_tran['timestamp']) , 0 , 19);
//                                    $api_tran_ctime_CDT  = date('Y-m-d H:i:s',strtotime($api_tran_ctime_real . ' -5 hour'));
                                    $api_tran_amount = $v_tran['amount'];
                                    $approvalCode    = $v_tran['approvalCode'] ?? '';
                                    $api_tran_shop   = $v_tran['merchantName'] ?? '';
                                    $merchantMcc     = $v_tran['merchantMcc'] ?? '';

                                    if($api_tran_status == "PENDING"){
                                        if($api_tran_type == 'authorization'){
                                            $api_tran_status = 'Authorized';
                                        }
                                    }else if($api_tran_status == "DECLINED"){
                                        if($api_tran_type == 'authorization'){
                                            //正常消费拒绝
                                            $api_tran_status = 'Declined';
                                        }
                                    }else if($api_tran_status == "COMPLETION"){
                                        if($api_tran_type == 'authorization.clearing'){
                                            //正常消费结算
                                            $api_tran_status = 'Posted';
                                        }else if($api_tran_type == 'refund.authorization.clearing'){
                                            //正常退款结算
                                            $api_tran_status = 'Credit';
                                        }
                                    }else if($api_tran_status == "CLEARED"){
                                        if($api_tran_type == 'authorization.reversal'){
                                            //正常撤销
                                            $api_tran_status = 'Reversal';
                                        }else if($api_tran_type == 'authorization.reversal.issuerexpiration') {
                                            $api_tran_status = 'Reversal';
                                        }
                                    }
                                    $data[] =[
                                        'app_code'      => $approvalCode,
                                        'idMatchNumber' => $api_tran_token,
                                        'tran_type'     => $api_tran_type,
                                        'tran_status'   => $api_tran_status,
                                        'amount_auth'   => $api_tran_amount,
                                        'amount_post'   => '',
                                        'shopping'      => $api_tran_shop,
                                        'desc'          => $v_tran['description']??'',
                                        'reversal_flag' => '',
                                        'ctime'         => $timestamp,
                                        'utime'         => '',
                                        'mcc'           => $merchantMcc
                                    ];
                                }
                            }
                        }

                    }else{
                        //查询出此卡已经审核的退款
                        $credit_list = Db::name('cards_trans_credit')->where([
                            "card_num"      => $card_num,
                            "credit_status" => 1
                        ])->select()->toArray();
                        $idMatchNumberArray = [];
                        if($credit_list){
                            foreach ($credit_list as $k_credit=>$v_credit){
                                $idMatchNumberArray[] = $v_credit['idMatchNumber'];
                            }
                        }
                        //api查询卡余额
                        $card_detail_param         = [
                            "user_id"       => $user_id,
                            "action_type"   => "searchExpDate2",
                            "card_type"     => $card_type,
                            "bank_type"     => $bank_type,
                            "post_param"    => [
                                "card_num"  => $card_num,
                            ]
                        ];
                        $search_card_detail_api = PublicApi::requestApi('Comdata',$card_detail_param);
                        $return_blog_detail    = $search_card_detail_api['blog'];
                        $return_list_detail    = $search_card_detail_api['list'];
                        if($return_blog_detail) {
                            $result['param']['balance'] = $return_list_detail['cycleAmountLimitAvailable'] ?? 0.00;
                            $result['param']['limit']   = $return_list_detail['cycleAmountLimit'] ?? 0.00;
                            $result['param']['status']   = $return_list_detail['cardStatus'] ?? 'NULL';
                        }
                        //搜索日志
                        if(!empty($date_time)){
                            $time_list = explode(' _ ' , $date_time);
                            $start_time = $time_list[0];
                            $end_time   = $time_list[1];
                            $data = self::getTimeTran($card_type,$bank_type,$card_num,$start_time,$end_time);
                        }else{
                            $end_time1   = date('Y-m-d');
                            $start_time1 = date("Y-m-d" , strtotime("-45 day"));
                            $data = self::getTimeTran($card_type,$bank_type,$card_num,$start_time1,$end_time1);
                            $start_time2 = date("Y-m-d" , strtotime("-90 day"));
                            $end_time2 = date("Y-m-d" , strtotime("-45 day"));
                            $data2 = self::getTimeTran($card_type,$bank_type,$card_num,$start_time2,$end_time2);
                            foreach ($data as $kkk=>$vvv){
                                array_push($data2 , $vvv);
                            }
                            $data= $data2;
                            $start_time = $start_time2;
                            $end_time   = $end_time1;
                        }
                        if($data){
                            foreach ($data as $k_data=>&$v_data){
                                if(in_array($v_data['idMatchNumber'] , $idMatchNumberArray)){
                                    $v_data['is_check'] = 1;
                                }
                            }
                        }
                        $result['param']['time'] = $start_time . '--' .$end_time;
                    }
                }
            }
            if(!empty($tran_status)){
                $new_data =[];
                foreach ($data as $k_data=>&$v_data){
                    switch ($tran_status){
                        case 'Authorized':
                            if($v_data['tran_status']=='Authorized' && $v_data['tran_status']=='N'){
                                $new_data[] = $v_data;
                            }
                            break;
                        case 'Posted':
                            if($v_data['tran_status']=='Posted'){
                                $new_data[] = $v_data;
                            }
                            break;
                        case 'Declined':
                            if($v_data['tran_status']=='Declined'){
                                $new_data[] = $v_data;
                            }
                            break;
                        case 'Credit':
                            if($v_data['tran_status']=='Credit'){
                                $new_data[] = $v_data;
                            }
                            break;
                        case 'Reversal':
                            if($v_data['tran_status']=='Authorized' && $v_data['tran_status'] !='N'){
                                $new_data[] = $v_data;
                            }
                            break;
                    }
                }
                $data = $new_data;
            }
            $result['data']  = array_reverse($data);
            $result['count'] = count($data);
            return $result;
        }
        View::assign([
            'tran_type'       => ['Authorized' ,
                'Posted' ,
                'Declined',
                'Credit',
                'Reversal',
            ],
        ]);
        return View::fetch();
    }

    public function searchTransAll()
    {
        if($this->request->isAjax()){
            $fcModel = new SearchTrans();
            return $fcModel->tableDataAdmin(input('param.'));
        }

        View::assign([
            'tran_type'       => ['Authorized' ,
                'Posted' ,
                'Declined',
                'Credit',
                'Reversal',
            ],
            'card_type'       => ['556305' ,
                '556766' ,
                '558068',
                '531847',
                '556735',
                '527811',
            ],
        ]);

        return View::fetch();
    }

    public function getTransAll()
    {
        $param      = input('param.');
        $card_type  = $param['card_type'] ?? '';
        $date_time  = trim(input('post.datetime', ''));
        if(!empty($card_type)){
            $credit_list = Db::name('cards_trans_credit')->where([
                "credit_status" => 1
            ])->select()->toArray();
            $idMatchNumberArray = [];
            if($credit_list){
                foreach ($credit_list as $k_credit=>$v_credit){
                    $idMatchNumberArray[] = $v_credit['idMatchNumber'];
                }
            }
            //获取倒user_id
            $card_list = Db::name('cards')->where([
                "card_type" => $card_type
            ])->select()->toArray();
            $card_type_user = [];
            if($card_list){
                foreach ($card_list as $k_c=>$v_c){
                    $card_type_user[$v_c['card_num']] = $v_c['user_id'];
                }
            }

            if(!empty($date_time)){
                $time_list = explode(' _ ' , $date_time);
                $start_time = $time_list[0];
                $end_time   = $time_list[1];
            }else{
                $end_time   = date('Y-m-d');
                $start_time = date("Y-m-d" , strtotime("-45 day"));
            }
            $data = self::getTimeTranAll($card_type,$start_time,$end_time);
            if($data){
                foreach ($data as $k_data=>&$v_data){
                    if(in_array($v_data['idMatchNumber'] , $idMatchNumberArray)){
                        $v_data['is_check'] = 1;
                    }
                    $v_data['user_id'] = $card_type_user[$v_data['card_num']] ?? '';
                }
                Db::name('search_trans')->where(['card_type' => $card_type])->delete();
                $re = Db::name('search_trans')->insertAll($data);
                if($re){
                    return $this->scs('存储成功.');
                }else{
                    return $this->err('存储错误.');
                }
            }else{
                return $this->err('数据错误.');
            }

        }else{
            return $this->err('卡头不存在.');
        }
    }

    private static function getTimeTran($card_type,$bank_type,$card_num,$start_time,$end_time)
    {
        $data = [];
        $param      = [
            "user_id"           => 0,
            "action_type"       => "search_trans_test",
            "card_type"         => $card_type,
            "bank_type"         => $bank_type,
            "post_param"  => [
                "card_num"   => $card_num,
                "startDate"  => $start_time,
                "endDate"    => $end_time,
            ]
        ];
        $send_api= PublicApi::requestApi('Comdata',$param);
        $return_blog    = $send_api['blog'];
        $return_list    = $send_api['list'];
        if($return_blog){
            foreach ($return_list as $k=>$v){
                $postedDate = $v['postedDate'] ?? '';
                $utime      = !empty($postedDate) ? $v['postedDate'] . ' ' . $v['postedTime'] : '';
                $shopping   = $v['acceptLocation'] ?? '';
                $ctime      = $v['transactionDate'] . ' ' . $v['transactionTime'];
                $reversalFlag = $v['reversalFlag'];
                $current_status = $v['transactionStatus'];
                $preAuthAmount  = $v['preAuthAmount'];
                $postedAmount   = $v['postedAmount'];
                $idMatchNumber  = $v['idMatchNumber'] ?? '';
                $approvalCode  = $v['approvalCode'] ?? '';
                $correctiveAction = '';
                if($v['transactionStatus'] == 'Declined'){
                    $correctiveAction = $v['correctiveAction'] ?? '';
                    if(empty($correctiveAction)){
                        $correctiveAction = $v['declineMessage'] ?? '';
                    }
                }
                $data[] =[
                    'app_code'      => $approvalCode,
                    'idMatchNumber' => $idMatchNumber,
                    'tran_status'   => $current_status,
                    'amount_auth'   => $preAuthAmount,
                    'amount_post'   => $postedAmount,
                    'shopping'      => $shopping,
                    'desc'          => $correctiveAction,
                    'reversal_flag' => $reversalFlag,
                    'ctime'         => $ctime,
                    'utime'         => $v['transactionStatus'] == 'Declined' ? '' : $utime,
                    'mcc'           => ''
                ];
            }
        }
        return $data;
    }

    private static function getTimeTranAll($card_type,$start_time,$end_time)
    {
        $data = [];
        $param      = [
            "user_id"           => 0,
            "action_type"       => "search_trans_all",
            "card_type"         => $card_type,
            "post_param"  => [
                "startDate"  => $start_time,
                "endDate"    => $end_time,
            ]
        ];
        $send_api= PublicApi::requestApi('Comdata',$param);
        $return_blog    = $send_api['blog'];
        $return_list    = $send_api['list'];
        if($return_blog){
            foreach ($return_list as $k=>$v){
                $postedDate = $v['postedDate'] ?? '';
                $utime      = !empty($postedDate) ? $v['postedDate'] . ' ' . $v['postedTime'] : '';
                $shopping   = $v['acceptLocation'] ?? '';
                $ctime      = $v['transactionDate'] . ' ' . $v['transactionTime'];
                $reversalFlag = $v['reversalFlag'];
                $current_status = $v['transactionStatus'];
                $preAuthAmount  = $v['preAuthAmount'];
                $postedAmount   = $v['postedAmount'];
                $idMatchNumber  = $v['idMatchNumber'] ?? '';
                $approvalCode  = $v['approvalCode'] ?? '';
                $card_num       = $v['cardNumber'] ?? '';
                $correctiveAction = '';
                if($v['transactionStatus'] == 'Declined'){
                    $correctiveAction = $v['correctiveAction'] ?? '';
                    if(empty($correctiveAction)){
                        $correctiveAction = $v['declineMessage'] ?? '';
                    }
                }
                $data[] =[
                    'app_code'      => $approvalCode,
                    'idMatchNumber' => $idMatchNumber,
                    'status'   => $current_status,
                    'amount_auth'   => $preAuthAmount,
                    'amount_post'   => $postedAmount,
                    'shopping'      => $shopping,
                    'desc'          => $correctiveAction,
                    'flag' => $reversalFlag,
                    'time_auth'         => $ctime,
                    'time_post'         => $v['transactionStatus'] == 'Declined' ? '' : $utime,
                    'card_type'     => $card_type,
                    'card_num'      => $card_num
                ];
            }
        }
        return $data;
    }

    /**
     * 删除vva平台外的556766卡
     * @return \think\response\Json
     */
    public function delCard()
    {
        $data           = input('param.');
        $card_num       = trim($data['card_num']);
        $card_balance   = $data['card_balance'];
        $card_used      = $data['card_used'];
        $update_card_param      = [
            "user_id"       => 0,
            "action_type"   => 'card_del',
            "card_type"     => 556766,
            "post_param"  => [
                "card_num"  => $card_num
            ]
        ];
        $create_card_api= PublicApi::requestApi('Comdata',$update_card_param);
        $return_blog    = $create_card_api['blog'];
        if($return_blog) {
            //记录管理员操作日志
            ManageLog::saveManageLog([
                'manage_id' => $this->manage_id,
                'desc' => 'manage_card_del',
                'time' => getUtcTime(),
                'content' => json_encode([
                    'card_num' => $card_num,
                    'username' => 'other platform'
                ])
            ]);
            Db::name('cards_del')->save([
                'card_num'      => $card_num,
                'card_balance'  => $card_balance,
                'card_used'     => $card_used,
                'plat'          => 1, //1代表外平台
                'ctime'         => getUtcTime()
            ]);
        }
        $num = 0;
        if($num){
            return $this->scs("{$num} 张卡删除成功.");
        }else{
            return $this->err('卡删除失败.');
        }
    }

    public function testAddCard()
    {
        if($this->request->isAjax()){
            $data           = input('param.');
            $card_type       = trim($data['card_type']);
            if(empty($card_type)){
                return $this->err('卡头不能为空.');
            }
            $exp_time = date('Y-m-01',strtotime('+23 month'));
            $create_card_param      = [
                "user_id"       => 0,
                "action_type"   => "addCard",
                "request_data"  => [
                    "MerchantGuid"   => "6423ae42-1628-4ca1-a5fb-830da34177de",
                    "FirstName"      => 'start' . $card_type,
                    "LastName"       => 'end' . $card_type,
                    "Address1" => "134 haines st",
                    "Address2"=> "",
                    "City"=> "Nashua",
                    "State"=> "NH",
                    "Zipcode"=> "03060",
                    "Country"=> "US",
                    "LimitWindow"=> "Lifetime",
                    "UsageLimit"=> 99,
                    "AmountLimit"=> 10.00,
                    "ExpirationDate"=> $exp_time,
                    "TerminateDate"=> $exp_time,
                    "PurchaseType"=> "98",
                    "SequenceNumber"=> "Sample-seq-1",
                    "OrderNumber"=>"test" .  $card_type . substr(getUtcTime(), -6),
                    "CustomerId"=>"Ken Pullin",
                    "NonDomesticSupplier"=> false,
                    "cardBin"=>$card_type
                ]
            ];
            $create_card_api= PublicApi::requestApi('Connexpay',$create_card_param);
            $return_blog    = $create_card_api['blog'];
            $return_list    = $create_card_api['list'];
            if($return_blog){
                $card_num           = $return_list['card']['accountNumber'];
                return $this->scs("成功创建卡 : " . $card_num );
            }else{
                return $this->err('卡删除失败.');
            }
        }
        return View::fetch();
    }

    public function homeList()
    {
        if($this->request->isAjax()){
            $model = new UserCashLog();
            return $model->homeList(input('param.'));
        }
        return View::fetch();
    }

    public function homeListTwo()
    {
        if($this->request->isAjax()){
            $model = new UserCashLog();
            return $model->homeListTwo(input('param.'));
        }
        return View::fetch();
    }

    public function homeOne()
    {
        $data = input('param.');
        $re = UserCashLog::getHomeDataOne($data);
        if($re){
            return $this->scs("统计成功.");
        }else{
            return $this->err("统计失败.");
        }
    }

    public function homeUp()
    {
        $data = input('param.');
        $is_all_up = $data['is_all_up'];
        if($is_all_up == 0){
            if(empty($data['datetime'])) return $this->err("时间不能为空.");
        }
        $re = UserCashLog::getHomeData($data);
        if($re){
            return $this->scs("统计成功.");
        }else{
            return $this->err("统计失败.");
        }
    }

    public function searchCards()
    {
        if($this->request->isAjax()){

            //第一次查询所有卡，并删除
            //self::firstDel();
            //self::secondDel();
            //self::threeDel();

            $list = Db::name('cards_search')
                ->order('id asc')
                ->select()
                ->toArray();
            foreach ($list as $k=>&$v){
                $v['card_num'] = "'" . $v['card_num'] . "'";
            }
            return $result = [
                'code'  => 0,
                'msg'   => lang('get info success'),
                'data'  => $list,
                'count' => count($list),
            ];
        }
        return View::fetch();
    }

    public static function firstDel()
    {
        $aa = "5567665511822953
                5567665537450425";
        $bb = explode("\n" , $aa);
        $card_list =[];
        foreach ($bb as $kk=>$vv){
            if(!empty($vv)){
                $card_list[] = trim($vv);
            }
        }
        $ctime = getUtcTime();
        $search_list = Db::name('cards_search')->select()->toArray();
        $search_card = [];
        if($search_list){
            foreach ($search_list as $k_search=>$v_search){
                $search_card[] = $v_search['card_num'];
            }
        }

        foreach ($card_list as $k=>$v){
            if(!in_array($v , $search_card)){
                $send_param         = [
                    "user_id"       => 0,
                    "action_type"   => "searchExpDate",
                    "card_type"     => 556766,
                    "bank_type"     => 1,
                    "post_param"    => [
                        "card_num"  => $v,
                    ]
                ];
                $check_card_api = PublicApi::requestApi('Comdata',$send_param);
                $return_blog    = $check_card_api['blog'];
                $return_list    = $check_card_api['list'];
                if($return_blog) {
                    $api_amount = $return_list['cycleAmountLimitAvailable'];
                    $api_amount_total = $return_list['cycleAmountLimit'];
                    $api_cardStatus = $return_list['cardStatus'];
                    $cardExpiration = $return_list['cardExpiration'];
                    $cardExpiration_strto = strtotime($cardExpiration . " 00:00:00");
                    $new_status = '';
                    if($cardExpiration_strto - $ctime >=0){
                        if($api_cardStatus == 'A'){
                            $update_card_param      = [
                                "user_id"       => 0,
                                "action_type"   => 'card_del',
                                "card_type"     => 556766,
                                "bank_type"     => 1,
                                "post_param"  => [
                                    "card_num"  => $v
                                ]
                            ];
                            $del_card_result= PublicApi::requestApi('Comdata',$update_card_param);
                            $del_card_blog    = $del_card_result['blog'];
                            if($del_card_blog){
                                $new_status = 'C';
                            }
                        }
                    }
                    Db::name('cards_search')->save([
                        'card_num'      => $v,
                        'balance'       => $api_amount,
                        'balance_total' => $api_amount_total,
                        'cardExpiration'=> $cardExpiration,
                        'status'        => $api_cardStatus,
                        'new_status'    => $new_status
                    ]);
                }
            }
        }
    }
    public static function secondDel()
    {
        $list = Db::name('cards_search')
            ->where("new_status =''")
            ->select()
            ->toArray();
        if($list){
            foreach ($list as $k=>$v){
                $id = $v['id'];
                $card_num = $v['card_num'];
                if($v['status'] == 'B' && $v['new_status'] == ''){
                    $data       = [
                        "user_id"       => 0,
                        "action_type"   => 'card_active_new',
                        "card_type"     => 556766,
                        "bank_type"     => 1,
                        "post_param"    => [
                            "card_num"       => $card_num
                        ]
                    ];
                    $update_result = PublicApi::requestApi('Comdata' , $data);
                    $update_result_blog = $update_result['blog'];
                    if($update_result_blog){
                        $update_card_param      = [
                            "user_id"       => 0,
                            "action_type"   => 'card_del',
                            "card_type"     => 556766,
                            "bank_type"     => 1,
                            "post_param"  => [
                                "card_num"  => $card_num
                            ]
                        ];
                        $del_card_result= PublicApi::requestApi('Comdata',$update_card_param);
                        $del_card_blog    = $del_card_result['blog'];
                        if($del_card_blog){
                            Db::name('cards_search')->where(['id'=>$id])
                                ->update(['new_status'=>'C']);
                        }
                    }
                }
            }
        }
    }

    public static function threeDel(){
        $list = Db::name('cards_search')
            ->select()
            ->toArray();
        if($list){
            foreach ($list as $k=>$v){
                if($v['old_status'] == ''){
                    $card_num = trim($v['card_num'] , '\'');
                    $old_id   = $v['id'];
                    $send_param         = [
                        "user_id"       => 0,
                        "action_type"   => "searchExpDate",
                        "card_type"     => 556766,
                        "bank_type"     => 1,
                        "post_param"    => [
                            "card_num"  => $card_num,
                        ]
                    ];
                    $check_card_api = PublicApi::requestApi('Comdata',$send_param);
                    $return_blog    = $check_card_api['blog'];
                    $return_list    = $check_card_api['list'];
                    if($return_blog) {
                        $api_cardStatus = $return_list['cardStatus'];

                        Db::name('cards_search')->where(['id' => $old_id])
                            ->update([
                            'old_status'      => $api_cardStatus
                            ]);
                    }
                }

            }
        }
    }

    public function userCashError()
    {
        if($this->request->isAjax()){
            $fcModel = new UserCashError();
            return $fcModel->tableDataAdmin(input('param.'));
        }
        return View::fetch();
    }

    public function xfUserCash()
    {
        $param      = input('param.');
        $user_name  = $param['username'] ?? '';

        if(!empty($user_name)){
            try {
                $user_list = Db::name('user')->where(['username'=>trim($user_name)])->find();
                if(!empty($user_list)){
                    $user_id = $user_list['id'];
                    $username= $user_list['username'];
                    $cash_list = Db::name('user_cash_error')->where(['user_id' => $user_id,'type'=>0])->order('id desc')->limit(1)->find();
                    $max_id = str_replace('u', "", $cash_list['type_id']);

                    $pay_where = "user_id={$user_id}";
                    if(!empty($max_id)){
                        $pay_where .= " and id > {$max_id}";
                        $amount_ok    = $cash_list['balance'] - $cash_list['amount'];
                    }else{
                        $amount_ok    = 0;
                    }
                    $pay_log = Db::name('user_cash_log')
                        ->where($pay_where)->order('id asc')->select()->toArray();
                    foreach ($pay_log as $k=>$v){
                        $type       = $v['type'];
                        $id         = $v['id'];
                        $balance    = $v['balance'];
                        $time       = $v['ctime'];
                        if($type == 1){
                            $amount_ok -= $v['amount'];
                            $amount_error = -$v['amount'];
                        }else{
                            $amount_ok += $v['amount'];
                            $amount_error = $v['amount'];
                        }
                        $amount_ok = getSprintf(round($amount_ok,2));

                        if($amount_ok - $balance != 0){
                            Db::name('user_cash_error')->save([
                                'user_id'   => $user_id,
                                'username'  => $username,
                                'amount_error' => $amount_error,
                                'amount'    => $amount_ok - $balance,
                                'balance'   => $amount_ok,
                                'time_error'=> $time,
                                'type_id'   => 'u' . $id,
                            ]);
                            $amount_ok = $balance;
                        }
                    }
                }
                return $this->scs('ok.');
            }catch (\Exception $e){
                return $this->err('数据操作错误.');
            }
        }else{
            return $this->err('用户不存在.');
        }
    }


    public function userSort()
    {
        if($this->request->isAjax()){
            $param      = input('param.');
            $user_name  = $param['user_name'] ?? '';

            $result = [
                'code'  => 0,
                'msg'   => lang('get info success'),
                'data'  => [],
                'count' => 0,
            ];
            if(!empty($user_name)){
                $user_id = Db::name('user')->where(['username' => trim($user_name)])->value('id');

                $list = Db::name('user_cash_log')
                    ->where(['user_id' => $user_id])->order('id asc')->select()->toArray();
                $list_new   = [];
                $list_1     = [];
                $balance    = 0;
                foreach ($list as $k=>$v){
                    $list_new['type'] = $v['type'];
                    if($list_new['type'] == 1){
                        $amount = -$v['amount'];
                        $balance -= $v['amount'];
                    }else{
                        $amount = $v['amount'];
                        $balance += $v['amount'];
                    }
                    $list_new['amount'] = $amount;
                    $list_new['balance'] = getSprintf($balance);
                    $list_new['desc'] = $v['desc'];
                    $list_new['ctime'] = $v['ctime'];
                    $list_1[] = $list_new;
                }
                return $result = [
                    'code'  => 0,
                    'msg'   => lang('get info success'),
                    'data'  => array_reverse($list_1),
                    'count' => count($list_1),
                ];
            }
            return $result;

        }
        return View::fetch();
    }

    public function userTran()
    {
        if($this->request->isAjax()){
            $model = new CardsTransOne();
            return $model->tableDataAdmin(input('param.'));
        }
        View::assign([
            'tran_type'       => ['Authorized' ,
                'Posted' ,
                'Declined',
                'Credit',
                'Reversal'
            ],
        ]);
        return View::fetch();
    }

    public function userTranDiff()
    {
        if($this->request->isAjax()){
            $model = new CardsTransTwo();
            return $model->tableDataAdmin(input('param.'));
        }
        View::assign([
            'tran_type'       => ['Authorized' ,
                'Posted' ,
                'Declined',
                'Credit',
                'Reversal'
            ],
        ]);
        return View::fetch();
    }

    public function userUpdate()
    {
        if($this->request->isAjax()){
            $param      = input('param.');
            $card_num   = $param['card_num'] ?? '';
            $tran_id    = $param['tran_id'] ?? '';
            if(!empty($tran_id)){
                $list = $re = Db::name('cards_trans')
                    ->where([
                        'card_num'  => trim($card_num),
                        'id'        => trim($tran_id)
                    ])->find();
                if(!empty($list)){
                    $re = Db::name('cards_trans')
                        ->where([
                            'card_num'  => trim($card_num),
                            'id'        => trim($tran_id)
                        ])->update(['reversal_flag' =>'X']);
                    if($re){
                        return $this->scs('ok.');
                    }else{
                        return $this->err('更新失败.');
                    }
                }else{
                    return $this->err('更新失败.找不到数据2.');
                }
            }else{
                return $this->err('更新失败.找不到数据1.');
            }
        }
        return View::fetch();
    }

    public function addCashError()
    {
        if($this->request->isAjax()){
            $param          = input('param.');
            $user_name      = trim($param['user_name']);
            $type           = trim($param['type']);
            $amount         = trim($param['amount']);
            $amount_ok      = trim($param['amount_ok']);
            $amount_current = trim($param['amount_current']);
            $time_error     = strtotime(trim($param['time_error']));
            $table_id       = trim($param['table_id']);
            $desc           = trim($param['desc']);

            $user_list      = Db::name('user')->where(['username'=>$user_name])->find();
            if(!empty($user_list)){
                $re = Db::name('user_cash_error')->save([
                    'user_id'   => $user_list['id'],
                    'username'  => $user_list['username'],
                    'amount_error' => $amount,
                    'amount'    => $amount_ok,
                    'balance'   => $amount_current,
                    'time_error'=> $time_error,
                    'type'      => $type,
                    'type_id'   => 'c' . $table_id,
                    'desc'      => $desc
                ]);
                if($re){
                    return $this->scs('ok.');
                }else{
                    return $this->err('更新失败.');
                }
            }else{
                return $this->err('更新失败.找不到用户.');
            }
        }
        return View::fetch();
    }

    public function xfCardAmount()
    {
        if($this->request->isAjax()){
            $fcModel = new MonitorCard();
            return $fcModel->tableDataAdmin(input('param.'));
        }
        return View::fetch();
    }

    public function xfCardAmountDiff()
    {
        $fcModel = new MonitorCardDiff();
        return $fcModel->tableDataAdmin(input('param.'));
    }

    public function searchCardAmount()
    {
        $param      = input('param.');
        $user_name  = $param['username'] ?? '';
        if(!empty($user_name)){
            $user_name = trim($user_name);
            $user_id = Db::name('user')->where(['username' => $user_name])->value('id');

            if(!empty($user_id)){
                $card_list = Db::name('cards')
                    ->where("user_id ={$user_id}")
                    ->select()->toArray();
                $ctime = getUtcTime();

                $mon_lst = Db::name('monitor_card')
                    ->where("user_id ={$user_id}")
                    ->select()->toArray();
                $mon_array =[];
                if($mon_lst){
                    foreach ($mon_lst as $k_diff=>$v_diff){
                        $mon_array[] = $v_diff['card_num'];
                    }
                }

                foreach ($card_list as $k=>$v){
                    $card_type      = $v['card_type'];
                    $bank_type      = $v['bank_type'];
                    $card_num       = $v['card_num'];
                    $card_token     = $v['card_token'];
                    $balance        = $v['balance'];
                    $balance_limit  = $v['balance_account'];

                    $balance_api            = 0;
                    $balance_limit_api    = 0;

                    if(!in_array($card_num , $mon_array)){
                        if($bank_type == 3){
                            $send_param         = [
                                "user_id"       => $user_id,
                                "card_num"      => $card_num,
                                "cardGuid"      => $card_token,
                                "action_type"   => "getCardDetail"
                            ];

                            $check_card_api = PublicApi::requestApi('Connexpay',$send_param);
                            $return_blog    = $check_card_api['blog'];
                            $return_list    = $check_card_api['list'];
                            if($return_blog) {
                                $balance_api = $return_list['availableBalance'];
                                $balance_limit_api = $return_list['amountLimit'];
                            }
                        }else{
                            $send_param         = [
                                "user_id"       => $user_id,
                                "action_type"   => "searchExpDate2",
                                "card_type"     => $card_type,
                                "bank_type"     => $bank_type,
                                "post_param"    => [
                                    "card_num"  => $card_num,
                                ]
                            ];
                            $check_card_api = PublicApi::requestApi('Comdata',$send_param);
                            $return_blog    = $check_card_api['blog'];
                            $return_list    = $check_card_api['list'];
                            if($return_blog) {
                                $balance_api = $return_list['cycleAmountLimitAvailable'];
                                $balance_limit_api = $return_list['cycleAmountLimit'];
                            }
                        }
                        Db::name('monitor_card')->save([
                            'user_id'   =>  $user_id,
                            'username'  =>  $user_name,
                            'card_num'  =>  $card_num,
                            'bank_type' =>  $bank_type,
                            'balance'           =>  $balance,
                            'balance_limit'     =>  $balance_limit,
                            'balance_api'       =>  $balance_api,
                            'balance_limit_api' =>  $balance_limit_api,
                            'ctime'         => $ctime
                        ]);
                        if($balance_api - $balance != 0 || $balance_limit_api - $balance_limit !=0){
                            Db::name('monitor_card_diff')->save([
                                'user_id'   =>  $user_id,
                                'username'  =>  $user_name,
                                'card_num'  =>  $card_num,
                                'bank_type' =>  $bank_type,
                                'balance'           =>  $balance,
                                'balance_limit'     =>  $balance_limit,
                                'balance_api'       =>  $balance_api,
                                'balance_limit_api' =>  $balance_limit_api,
                                'ctime'         => $ctime
                            ]);
                        }
                    }
                }
                return $this->scs('ok.');
            }else{
                return $this->err('用户不存在.');
            }
        }else{
            return $this->err('用户名不能为空.');
        }
    }

    public function updateUserTran()
    {
        $param      = input('param.');
        $user_name  = $param['username'] ?? '';

        if(!empty($user_name)){
            $user_id = Db::name('user')->where(['username' => trim($user_name)])->value('id');

            if(!empty($user_id)){
                $card_list = Db::name('cards')
                    ->where("user_id ={$user_id} and bank_type != 3")
                    ->select()->toArray();
                $list_new   = [];
                $list_1     = [];
                Db::query("TRUNCATE mar_cards_trans_one");

                foreach ($card_list as $k=>$v){
                    $ctime = $v['ctime'];
                    $card_type = $v['card_type'];
                    $bank_type = $v['bank_type'];
                    $card_num  = $v['card_num'];

                    $timeArray = self::TimeSet($ctime);
                    foreach ($timeArray as $k_time=>$v_time){
                        $start  = date('Y-m-d' , $v_time[0]);
                        $end    = date('Y-m-d' , $v_time[1]);
                        self::upTranLogAll($card_type , $bank_type , $card_num , $user_id ,$start , $end);
                    }
                    return $this->scs('ok.');
                }
            }else{
                return $this->err('用户不存在.');
            }
        }else{
            return $this->err('用户名不能为空.');
        }
    }

    public function updateUserCash()
    {
        $param      = input('param.');
        $user_name  = $param['username'] ?? '';

        if(!empty($user_name)){
            $user_id = Db::name('user')->where(['username' => trim($user_name)])->value('id');

            if(!empty($user_id)){
                $pay_log = Db::name('user_cash_log')
                    ->where("user_id={$user_id}")->order('id asc')->select()->toArray();
                $amount = 0;
                foreach ($pay_log as $k=>$v){
                    $type = $v['type'];
                    $id   = $v['id'];
                    if($type == 1){
                        $amount -= $v['amount'];
                    }else{
                        $amount += $v['amount'];
                    }
                    $amount = getSprintf(round($amount,2));
                    Db::name('user_cash_log')->where(['id'=>$id])->update(['balance'=>$amount]);
                }
                $re = Db::name('user')->where(['id'=>$user_id])->update(['balance'=>$amount]);
                if($re){
                    return $this->scs('Ok...---' . $amount);
                }else{
                    return $this->scs('Un Ok.');
                }
            }else{
                return $this->err('用户不存在.');
            }
        }else{
            return $this->err('用户名不能为空.');
        }
    }

    public static function TimeSet($ctime)
    {
        $time_add = 44*24*60*60;  //3801600
        $toTime   = getUtcTime();
        $count    = ceil(($toTime-$ctime)/$time_add);
        $list     = [];
        for($i=0;$i<$count;$i++){
            $list[] = [$ctime + $i*$time_add , $ctime + ($i+1)*$time_add];
        }
        return $list;
    }

    public static function upTranLogAll($card_type  , $bank_type , $card_num ,$user_id ,$start_time , $end_time)
    {
        $create_card_param      = [
            "user_id"       => $user_id,
            "action_type"   => "search_trans_test",
            "card_type"     => $card_type,
            "bank_type"     => $bank_type,
            "post_param"  => [
                "startDate"    => $start_time,
                "endDate"      => $end_time,
                "card_num"     => $card_num
            ]
        ];
        $request_api= PublicApi::requestApi("Comdata",$create_card_param);
        $blog       = $request_api['blog'] ?? false;
        if($blog){
            Db::startTrans();
            try {
                $list = $request_api['list'];
                $history_status = ['Authorized','Posted','Declined','Credit'];
                foreach ($list as $k=>$v){
                    $cardNumber = $v['cardNumber'];
                    $postedDate = $v['postedDate'] ?? '';
                    $transactionTime      = !empty($postedDate) ? $v['postedDate'] . ' ' . $v['postedTime'] : '';
                    $shopping   = $v['acceptLocation'] ?? '';
                    $authorizationTime      = $v['transactionDate'] . ' ' . $v['transactionTime'];
                    $reversalFlag = $v['reversalFlag'];
                    $current_status = $v['transactionStatus'];
                    $preAuthAmount  = $v['preAuthAmount'];
                    $post_amount  = $v['postedAmount'];
                    $idMatchNumber  = $v['idMatchNumber'] ?? '';
                    $correctiveAction = '';
                    if($v['transactionStatus'] == 'Declined'){
                        $correctiveAction = $v['correctiveAction'] ?? '';
                        if(empty($correctiveAction)){
                            $correctiveAction = $v['declineMessage'] ?? '';
                        }
                    }
                    $approvalCode = $v['approvalCode'];

                    $decline_error  = $api_elements_array['correctiveAction'] ?? '';

                    $insert_data =[
                        'user_id'       => $user_id,
                        'app_code'      => $approvalCode,
                        'card_num'      => $cardNumber,
                        'amount_auth'   => $preAuthAmount,
                        'amount_post'   => $post_amount,
                        'reversal_flag' => $reversalFlag,
                        'shopping'      => $shopping,
                        'ctime'         => $authorizationTime,
                        'bank_type'     => $bank_type,
                        'desc'          => $decline_error,//当状态为DECLINE,这里会有数据，否者为0
                        'idMatchNumber' => $idMatchNumber,
                    ];

                    if($current_status == 'Authorized'){
                        $auth_check = Db::name('cards_trans_one')->where([
                            'app_code'      => $v['approvalCode'],
                            'tran_token'    => $v['idMatchNumber'],
                            'tran_status'   => 'Authorized'
                        ])->find();
                        if(empty($auth_check)){
                            $insert_data += [
                                'tran_status'   => 'Authorized',
                            ];
                            Db::name('cards_trans_one')->save($insert_data);
                        }
                    }else if($current_status == 'Posted'){
                        $post_check = Db::name('cards_trans_one')->where([
                            'app_code'      => $v['approvalCode'],
                            'tran_token'    => $v['idMatchNumber']
                        ])->find();
                        if(empty($post_check)){
                            $insert_data += [
                                'tran_status'   => 'Posted',
                                'utime'         => $transactionTime,
                            ];
                            Db::name('cards_trans_one')->save($insert_data);
                        }
                    }else if($current_status == 'Declined'){
                        $decline_check = Db::name('cards_trans_one')->where([
                            'card_num'           => $card_num,
                            'tran_status'        => 'Declined',
                            'idMatchNumber'      => $idMatchNumber,
                        ])->find();
                        if(empty($decline_check)){
                            $insert_data += [
                                'tran_status'   => 'Declined',
                            ];
                            Db::name('cards_trans_one')->save($insert_data);
                        }
                    }else if($current_status == 'Credit'){
                        $credit_check = Db::name('cards_trans_one')->where([
                            'card_num'           => $card_num,
                            'idMatchNumber'      => $idMatchNumber,
                            'tran_status'        => 'Credit',
                        ])->find();
                        if(empty($credit_check)) {
                            $insert_data += [
                                'tran_status' => 'Credit',
                            ];
                            Db::name('cards_trans_one')->save($insert_data);
                        }
                    }
                }
                Db::commit();
            } catch (\Exception $e) {
                $error_msg = $e->getMessage();
                var_dump($error_msg);
                Db::rollback();
            }
        }
    }

}